package com.platform.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.platform.annotation.Authentication;
import com.platform.base.PageUtil;
import com.platform.base.R;
import com.platform.dao.UserDAO;
import com.platform.dao.UserRoleDAO;
import com.platform.dto.User;
import com.platform.dto.UserRole;
import com.platform.dto.UserSearchVo;
import com.platform.exception.BizException;
import com.platform.ext.mybatis.annotation.UseDataSource;
import com.platform.security.CipherUtil;
import com.platform.service.IUser;
import com.platform.utils.StringUtils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;

/**
 * 
 * <p> Title:Ygxx 实现</p>
 * <p> Description:  记录部门员工的信息</p>
 * <p> Copyright: Copyright (c) 2019 </p>
 * <p> Company: </p>
 *
 * @author wys
 * @version 1.0
 */
@Service

public class IUserImpl implements IUser{
	
	@Autowired
    private UserDAO<User> DAO;
	@Autowired
	private UserRoleDAO<UserRole> userRoleDAO;
    /** =========================== 数据库操作 ==================================== **/
    /**
     * 
     * selectAll(查询所有)
     * (这里描述这个方法适用条件 – 可选)
     * @return 
     * @return List
     * @exception 
     * @version  1.0.0
     */
    @Override
    @Authentication()//requiredPre="USERMANAGER_FIND"
//    @DataSource(slaveName="slave_kettle")
    public List<User> selectAll(Map<String,Object> map) {
        List<User> s = null;
        try {
            s = DAO.selectByMap(map);
        } catch (BizException e) {
            throw new BizException(e.getMessage());
        }
        return s;
    }

    /**
     * 
     * selectTotal(查询总条数)
     * (这里描述这个方法适用条件 – 可选)
     * @param map
     * @return 
     * @return Integer
     * @exception 
     * @version  1.0.0
     */
    @Override
    @Authentication(requiredPre="USERMANAGER_FIND")
    public Integer selectTotal(Map<String, Object> map) {
        Integer total = 0; 
        try {
            total = DAO.selectByMapCount(map);
        } catch (BizException e) {
            throw new BizException(e.getMessage());
        }
        return total;
    }

    /**
     * 
     * selectByPaging(分页查询)
     * (这里描述这个方法适用条件 – 可选)
     * @param pageUtil
     * @return 
     * @return List<YgxxDTO>
     * @exception 
     * @version  1.0.0
     */
    @Override
    @Authentication(requiredPre="USERMANAGER_FIND")
    public List<User> selectByPaging(PageUtil pageUtil) {
        List<User> pagingList = null;
        try {
            pagingList = DAO.selectByMapPaging(pageUtil);
        } catch (BizException e) {
            throw new BizException(e.getMessage());
        }
        return pagingList;
    }

    /**
     * 
     * delete(删除)
     * (这里描述这个方法适用条件 – 可选)
     * @param dto 
     * @return void
     * @exception 
     * @version  1.0.0
     */
    @Override
    @Authentication(requiredPre="USERMANAGER_DELETED")
    public boolean delete(User dto) {
        boolean flag = false;
        try {
            if(DAO.deleteByPrimaryKey(dto) > 0) {
            	if(userRoleDAO.deleteUserCode(dto.getId()) > 0) {
            		flag = true;
            	}
            }
        } catch (BizException e) {
            throw new BizException(e.getMessage());
        }
        return flag;
    }

    /**
     * 
     * update(修改)
     * (这里描述这个方法适用条件 – 可选)
     * @param dto 
     * @return void
     * @exception 
     * @version  1.0.0
     */
    @Override
    @Authentication(/*requiredPre="USERMANAGER_EDIT"*/)
    public boolean update(User dto) {
        boolean flag = false;
        try {
            if(!StringUtils.isEmpty(dto.getPassword())) {
                dto.setPassword(CipherUtil.generatePassword(dto.getPassword()));
            }
            if(DAO.updateBySelective(dto) > 0)
                flag = true;
            else 
                flag = false;
        } catch (BizException e) {
            throw new BizException(e.getMessage());
        }
        return flag;
    }

    /**
     * 
     * insert(新增)
     * (这里描述这个方法适用条件 – 可选)
     * @param dto 
     * @return void
     * @exception 
     * @version  1.0.0
     */
    @Override
    @Authentication(requiredPre="USERMANAGER_SAVE")
    public boolean insert(User dto) {
        boolean flag = false;
        try {
            dto.setPassword(CipherUtil.generatePassword(dto.getPassword()));
            if(DAO.insert(dto) > 0)
                flag = true;
            else 
                flag = false;
        } catch (BizException e) {
            throw new BizException(e.getMessage());
        }
        return flag;
    }
    
    @Override
    @UseDataSource()
    public R<?> insertByCreateAccount(User dto) {
        try { 
        	dto.setJobstate(1L);
        	dto.setTheme("systemManager");
        	dto.setLoginname(dto.getMobphone());
            dto.setPassword(CipherUtil.generatePassword(dto.getPassword()));
            if(DAO.insert(dto) > 0) {
            	//分配角色权限
            	Long roleCode = -1L;//角色编号
//            	2	信访办
//            	3	监察室办事人员
//            	4	监察室主任
//            	5	案件监督管理
//            	6	案件审查调查
            	switch(dto.getDeptcode().intValue()) {
            		case 14://信访室
            			roleCode = 2L;
            			break;
            		case 15://案件监督管理室
            			roleCode = 5L;
            			break;
            		case 16://案件审理室
            			roleCode = 6L;
            			break;
            		case 17://第一纪检监察室
            			break;
            		case 18://第二纪检监察室
            			break;
            		case 19://第三纪检监察室
            			break;
            		case 20://第四纪检监察室
            			break;
            		case 21://法规室
            			break;
            	}
            	if(roleCode == -1) {
            		UserRole userRole = new UserRole();
            		userRole.setUsercode(dto.getId());
            		userRole.setRolecode(roleCode);
            		userRole.setCreateDate(new Date(System.currentTimeMillis()));
            		userRole.setCreater("系统");
            		if(userRoleDAO.insert(userRole) > 0) {
            			return R.success("注册成功！！！");
            		}else {
            			return R.success("注册成功，但目前无法登录系统，请联系管理员");
            		}
            	}else {
            		return R.success("注册成功，但目前无法登录系统，请联系管理员");
            	}
            }else {
                return R.fail();
            }
        } catch (BizException e) {
            return R.fail(e.getMessage());
        }
    }

    @Override
    @Authentication/*(requiredPre="USERMANAGER_FIND")*/
    @UseDataSource()
    public User get(Object code) {
        User dto = null;
        try {
            dto = DAO.selectByPrimaryKey(code);
        } catch (BizException e) {
            throw new BizException(e.getMessage());
        }
        return dto;
    }
    
    @Override
    @Authentication
    @UseDataSource(slaveName="master")
    public User validateUserName(String userName) {
        User dto = null;
        try {
            dto = DAO.validateUserName(userName);
        } catch (BizException e) {
            throw new BizException(e.getMessage());
        }
        return dto;
    }

    @Override
    @Authentication
    @UseDataSource()
    public User validateUserNameAndPwd(String userName, String pwd) {
        User dto = null;
        try {
            Map<String,Object> map = MapUtil.newHashMap();
            map.put("loginname", userName);
            map.put("password", pwd);
            dto = DAO.validateUserNameAndPwd(map);
        } catch (BizException e) {
            throw new BizException(e.getMessage());
        }
        return dto;
    }
    
    @Override
    @Authentication
    public User selectUserByOpenId(String openId) {
    	return DAO.selectUserByOpenId(openId);
    }
    
    /**
     * @Title: saveLoginErrorCount   
     * @Description:  保存错误登录次数
     * @author: <a href="mailto:15909910367@163.com">吴先生</a>      
     * void
     */
    @Override
    @Authentication
    public void saveLoginErrorCount(Object userCode) {
    	DAO.saveLoginErrorCount(userCode);
    }
    /**
     * 
     * @Title: savePasswordErrorLastTime   
     * @Description: 保存最后一次输错密码时间
     * @author: <a href="mailto:15909910367@163.com">吴先生</a>      
     * void
     */
    @Override
    @Authentication
    public void savePasswordErrorLastTime(Object userCode) {
    	DAO.savePasswordErrorLastTime(userCode);
    }
    /**
     * @Title: saveLastLoginTime   
     * @Description: 最后登录时间  
     * @author: <a href="mailto:15909910367@163.com">吴先生</a>      
     * void
     */
    @Override
    @Authentication
    public void saveLastLoginTime(Object userCode) {
    	DAO.saveLastLoginTime(userCode);
    }
    
    /**
     * @Title: selectUserListByRole   
     * @Description: 根据用户角色查询用户信息 
     * @param pageUtil      
     * void
     */
    @Override
    @Authentication
    public R<?> selectUserListByRole(UserSearchVo userSearchVo,int start,int limit) {
    	PageUtil pg = new PageUtil();
    	pg.setPageIndex(start);
    	pg.setPageSize(limit);
    	pg.setParams(BeanUtil.beanToMap(userSearchVo));
    	List<User> datas = DAO.selectUserListByRole(pg);
    	return R.success(datas, pg.getTotal());
    }
}